<?php

declare(strict_types=1);

namespace Lenntc\Framework\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Lenntc\Framework\Constants\ErrorCode;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ErrorExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @param Throwable $throwable
     * @param ResponseInterface $response
     * @return mixed
     */
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // ##记录日志
        $this->logger->error(sprintf('%s[%s] in %s',$throwable->getMessage(),$throwable->getLine(),$throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());

        ##格式化输出
        $level = $throwable instanceof \ErrorException ? "error" : "hard";
        $data = ['code'=>ErrorCode::SERVER_ERROR, 'msg'=>"服务异常.". $level,'data'=>[],'time'=>time()];
        $dataStream = new SwooleStream(json_encode($data, JSON_UNESCAPED_UNICODE));

        ##阻止异常冒泡
        $this->stopPropagation();
        return $response->withHeader('Server', 'lenntc')
            ->withAddedHeader('Content-Type', 'application/json;charset=utf-8')
            ->withStatus(ErrorCode::getHttpCode(ErrorCode::SERVER_ERROR))
            ->withBody($dataStream);
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }

}